import 'package:flutter/material.dart';
import 'package:native_video_cache/native_video_cache.dart';
import 'video_player/video_player_controller.dart';
import 'video_player/video_player_widget.dart';
import 'utils/error_handler.dart';

/// 优化后的缓存演示 - 完全替代VideoPlayerDemo
/// 支持单视频播放模式和多视频管理模式
class OptimizedCacheDemo extends StatefulWidget {
  final String? videoUrl;
  final String? title;

  const OptimizedCacheDemo({
    super.key,
    this.videoUrl,
    this.title,
  });

  @override
  State<OptimizedCacheDemo> createState() => _OptimizedCacheDemoState();
}

class _OptimizedCacheDemoState extends State<OptimizedCacheDemo>
    with RouteAware {
  // 视频播放器相关
  late NativeAvPlayerController _controller;
  bool _isInitialized = false;
  bool _isManagerInitialized = false;
  String _status = '正在初始化缓存管理器...';

  // 缓存状态
  double _cacheProgress = 0.0;
  CacheStatus _cacheStatus = CacheStatus.none;

  // 错误信息
  VideoErrorInfo? _currentErrorInfo;

  // 测试URL列表（如果没有传入特定视频）
  final List<String> _testUrls = [
    'https://new-jp.oss-cn-hangzhou.aliyuncs.com/jp_video/%E7%A7%91%E4%B8%802.2.2%E7%A6%81%E4%BB%A4%E6%A0%87%E5%BF%97.mp4',
    'https://new-jp.oss-cn-hangzhou.aliyuncs.com/jp_video/%E7%A7%91%E4%B8%802.1.1%E4%BA%A4%E9%80%9A%E4%BF%A1%E5%8F%B7%E7%81%AF%E7%9A%84%E5%88%86%E7%B1%BB%E3%80%81%E6%9C%BA%E5%8A%A8%E8%BD%A6%E5%92%8C%E9%9D%9E%E6%9C%BA%E5%8A%A8%E8%BD%A6%E4%BF%A1%E5%8F%B7%E7%81%AF.mp4',
  ];

  // 当前播放的视频信息
  String get _currentVideoUrl => widget.videoUrl ?? _testUrls.first;
  String get _currentVideoTitle => widget.title ?? '优化的视频播放演示';

  // 是否为单视频模式（传入了特定视频）
  bool get _isSingleVideoMode => widget.videoUrl != null;

  // 监听器引用（用于清理）
  CacheProgressListener? _progressListener;
  CacheStatusListener? _statusListener;
  CacheErrorListener? _errorListener;

  @override
  void initState() {
    super.initState();
    if (_isSingleVideoMode) {
      // 单视频模式：按照VideoPlayerDemo的流程
      _initializeNativeVideoCacheManager();
    } else {
      // 多视频模式：初始化优化的缓存系统
      _initializeOptimizedCache();
    }
  }

  @override
  void dispose() {
    debugPrint('OptimizedCacheDemo: 开始清理资源...');

    // 1. 停止播放器
    if (_isInitialized) {
      _controller.dispose();
      debugPrint('OptimizedCacheDemo: 播放器已释放');
    }

    // 2. 停止所有缓存任务
    _stopAllCacheTasksSync();

    // 3. 清理监听器
    _cleanupListeners();

    // 4. 清理生命周期管理器
    for (final url in _testUrls) {
      AppLifecycleManager.instance.unregisterActiveUrl(url);
    }
    if (widget.videoUrl != null) {
      AppLifecycleManager.instance.unregisterActiveUrl(widget.videoUrl!);
    }

    // 5. 清理状态管理器
    if (!_isSingleVideoMode) {
      CacheStateManager.instance.clearAllStates();
    }

    // 6. 强制清理所有缓存管理器监听器（如果是多视频模式）
    if (!_isSingleVideoMode) {
      try {
        NativeVideoCacheManager.clearAllListeners();
        debugPrint('OptimizedCacheDemo: 已清理所有缓存管理器监听器');
      } catch (e) {
        debugPrint('OptimizedCacheDemo: 清理缓存管理器监听器失败: $e');
      }
    }

    debugPrint('OptimizedCacheDemo: 资源清理完成');
    super.dispose();
  }

  @override
  void didPop() {
    debugPrint('OptimizedCacheDemo: 页面被弹出，执行清理...');
    _forceCleanup();
    super.didPop();
  }

  @override
  void didPopNext() {
    debugPrint('OptimizedCacheDemo: 从其他页面返回');
    super.didPopNext();
  }

  @override
  void didPush() {
    debugPrint('OptimizedCacheDemo: 页面被推入');
    super.didPush();
  }

  @override
  void didPushNext() {
    debugPrint('OptimizedCacheDemo: 推入新页面，暂停缓存任务');
    _pauseCacheTasksIfNeeded();
    super.didPushNext();
  }

  /// 强制清理所有资源
  void _forceCleanup() {
    debugPrint('OptimizedCacheDemo: 执行强制清理...');

    // 停止所有缓存任务
    _stopAllCacheTasksSync();

    // 清理监听器
    _cleanupListeners();

    // 如果是多视频模式，强制清理所有监听器
    if (!_isSingleVideoMode) {
      try {
        NativeVideoCacheManager.clearAllListeners();
      } catch (e) {
        debugPrint('OptimizedCacheDemo: 强制清理监听器失败: $e');
      }
    }
  }

  /// 暂停缓存任务（如果需要）
  void _pauseCacheTasksIfNeeded() {
    if (!_isSingleVideoMode) {
      debugPrint('OptimizedCacheDemo: 暂停后台缓存任务');
      // 在多视频模式下，当用户导航到其他页面时暂停缓存
      // 这可以避免后台持续运行缓存任务
    }
  }

  /// 同步停止所有缓存任务
  void _stopAllCacheTasksSync() {
    debugPrint('OptimizedCacheDemo: 停止所有缓存任务...');

    // 停止所有测试URL的缓存
    for (final url in _testUrls) {
      try {
        NativeVideoCacheManager.stopCache(url);
        debugPrint('OptimizedCacheDemo: 已停止缓存 - $url');
      } catch (e) {
        debugPrint('OptimizedCacheDemo: 停止缓存失败 - $url: $e');
      }
    }

    // 如果是单视频模式，停止当前视频的缓存
    if (_isSingleVideoMode && widget.videoUrl != null) {
      try {
        NativeVideoCacheManager.stopCache(widget.videoUrl!);
        debugPrint('OptimizedCacheDemo: 已停止当前视频缓存 - ${widget.videoUrl}');
      } catch (e) {
        debugPrint('OptimizedCacheDemo: 停止当前视频缓存失败: $e');
      }
    }
  }

  /// 清理所有监听器
  void _cleanupListeners() {
    debugPrint('OptimizedCacheDemo: 清理监听器...');

    try {
      // 清理原生缓存管理器的监听器
      if (_progressListener != null) {
        NativeVideoCacheManager.removeProgressListener(_progressListener!);
        _progressListener = null;
        debugPrint('OptimizedCacheDemo: 进度监听器已清理');
      }

      if (_statusListener != null) {
        NativeVideoCacheManager.removeStatusListener(_statusListener!);
        _statusListener = null;
        debugPrint('OptimizedCacheDemo: 状态监听器已清理');
      }

      if (_errorListener != null) {
        NativeVideoCacheManager.removeErrorListener(_errorListener!);
        _errorListener = null;
        debugPrint('OptimizedCacheDemo: 错误监听器已清理');
      }

      // 清理状态管理器的监听器
      for (final url in _testUrls) {
        CacheStateManager.instance.clearState(url);
      }
      if (widget.videoUrl != null) {
        CacheStateManager.instance.clearState(widget.videoUrl!);
      }

      debugPrint('OptimizedCacheDemo: 监听器清理完成');
    } catch (e) {
      debugPrint('OptimizedCacheDemo: 清理监听器时出错: $e');
    }
  }

  /// 按照VideoPlayerDemo的方式初始化（单视频模式）
  Future<void> _initializeNativeVideoCacheManager() async {
    try {
      setState(() {
        _status = '正在初始化缓存管理器...';
      });

      // 先初始化 NativeVideoCacheManager
      await NativeVideoCacheManager.initialize(
        CacheConfig(
          maxCacheSize: 500 * 1024 * 1024, // 500MB
          maxConcurrentDownloads: 2,
          connectTimeout: 30000,
          readTimeout: 30000,
        ),
      );

      setState(() {
        _isManagerInitialized = true;
        _status = '缓存管理器初始化成功，正在初始化播放器...';
      });

      // 然后初始化播放器
      await _initializePlayer();
    } catch (e) {
      setState(() {
        _status = '缓存管理器初始化失败: $e';
      });
    }
  }

  /// 初始化优化的缓存系统（多视频模式）
  Future<void> _initializeOptimizedCache() async {
    try {
      setState(() {
        _status = '正在初始化优化的缓存系统...';
      });

      // 1. 配置系统
      const configuration = CacheConfiguration(
        global: GlobalConfig(
          maxCacheSize: 2 * 1024 * 1024 * 1024, // 2GB
          enableDebugLogging: true,
          enablePerformanceMonitoring: true,
        ),
        performance: PerformanceConfig(
          maxConcurrentDownloads: 5,
          maxActiveListeners: 100,
          maxCacheStates: 200,
        ),
        network: NetworkConfig(
          connectTimeout: 30000,
          readTimeout: 60000,
          maxRetryAttempts: 3,
          enableBackgroundCaching: true,
        ),
      );

      // 2. 初始化配置管理器
      CacheConfigurationManager.instance.initialize(configuration);

      // 3. 初始化各个管理器
      CacheStateManager.instance.initialize();
      CacheMemoryManager.instance.initialize(
        maxUrls: configuration.performance.maxCacheStates,
        maxMemoryUsage: 10 * 1024 * 1024, // 10MB
      );
      await CacheStabilityManager.instance.initialize();
      CachePerformanceMonitor.instance.initialize();
      AppLifecycleManager.instance.initialize();

      // 4. 初始化主缓存管理器
      await NativeVideoCacheManager.initialize(
        CacheConfig(
          maxCacheSize: configuration.global.maxCacheSize,
          cacheDirectory: configuration.global.cacheDirectory,
          maxConcurrentDownloads:
              configuration.performance.maxConcurrentDownloads,
          connectTimeout: configuration.network.connectTimeout,
          readTimeout: configuration.network.readTimeout,
        ),
      );

      // 5. 设置状态监听
      _setupStateListeners();

      // 如果是单视频模式，初始化播放器
      if (_isSingleVideoMode) {
        await _initializePlayer();
      }

      setState(() {
        _isManagerInitialized = true;
        _status = '优化的缓存系统初始化完成';
      });
    } catch (e) {
      setState(() {
        _status = '初始化失败: $e';
      });
    }
  }

  Future<void> _initializePlayer() async {
    if (!_isManagerInitialized) {
      setState(() {
        _status = '缓存管理器未初始化';
      });
      return;
    }

    _controller = NativeAvPlayerController();

    // 设置事件监听器
    _controller.onStateChanged = (state) {
      if (mounted) {
        setState(() {
          _status = _getStatusText(state);
          // 如果状态变为error，获取错误信息
          if (state == NativeAvPlayerState.error) {
            _currentErrorInfo = _controller.currentErrorInfo;
          } else {
            _currentErrorInfo = null;
          }
        });
      }
    };

    _controller.onError = (error) {
      debugPrint('播放器 onError: $error');
      if (mounted) {
        setState(() {
          _currentErrorInfo = _controller.currentErrorInfo;
        });

        // 如果有详细的错误信息，显示友好的错误提示，否则显示简单提示
        final errorMessage = _currentErrorInfo?.title ?? '播放错误: $error';
        ScaffoldMessenger.of(context)
          ..hideCurrentSnackBar()
          ..showSnackBar(
            SnackBar(
              content: Text(errorMessage),
              backgroundColor: Colors.red,
            ),
          );
      }
    };

    _controller.onProgressChanged = (position, duration) {
      // 可以在这里处理进度更新
    };

    // 缓存事件监听
    _controller.onCacheProgressChanged = (progress) {
      debugPrint('onCacheProgressChanged: $progress');
      if (mounted) {
        setState(() {
          _cacheProgress = progress;
        });
      }
    };

    _controller.onCacheStatusChanged = (status) {
      debugPrint('onCacheStatusChanged: $status');
      if (mounted) {
        setState(() {
          _cacheStatus = status;
        });
      }
    };

    try {
      await _controller.initialize(
        _currentVideoUrl,
        autoPlay: true,
        allowFullScreen: true,
        showControls: true,
      );

      setState(() {
        _isInitialized = true;
        _status = '播放器初始化成功';
        _currentErrorInfo = null;
      });
    } catch (e) {
      // 使用智能错误分析器分析初始化错误
      try {
        final errorInfo = await VideoErrorHandler.analyzeError(
          e.toString(),
          _currentVideoUrl,
        );
        setState(() {
          _currentErrorInfo = errorInfo;
          _status = errorInfo.title;
        });
      } catch (analysisError) {
        // 如果错误分析失败，使用默认错误信息
        setState(() {
          _status = '播放器初始化失败: $e';
          _currentErrorInfo = null;
        });
      }
    }
  }

  String _getStatusText(NativeAvPlayerState state) {
    switch (state) {
      case NativeAvPlayerState.idle:
        return '空闲';
      case NativeAvPlayerState.loading:
        return '加载中...';
      case NativeAvPlayerState.ready:
        return '准备就绪';
      case NativeAvPlayerState.playing:
        return '播放中';
      case NativeAvPlayerState.paused:
        return '已暂停';
      case NativeAvPlayerState.buffering:
        return '缓冲中...';
      case NativeAvPlayerState.error:
        return '播放错误';
      case NativeAvPlayerState.disposed:
        return '已释放';
    }
  }

  void _setupStateListeners() {
    // 监听统一状态变化
    CacheStateManager.instance.stateStream.listen((state) {
      debugPrint('状态变化: ${state.url} -> ${state.status} (${state.progress})');
    });

    // 为每个测试URL添加状态监听器
    for (final url in _testUrls) {
      CacheStateManager.instance.addListener(url, (state) {
        if (mounted) {
          setState(() {
            // 触发UI更新
          });
        }
      });
    }

    // 设置原生缓存管理器的监听器（用于多视频模式）
    _progressListener = (String url, double progress) {
      debugPrint('缓存进度: $url -> $progress');
      CacheStateManager.instance.updateState(url, progress: progress);
      if (mounted) {
        setState(() {
          // 触发UI更新
        });
      }
    };
    NativeVideoCacheManager.addProgressListener(_progressListener!);

    _statusListener = (String url, CacheStatus status) {
      debugPrint('缓存状态: $url -> $status');
      CacheStateManager.instance.updateState(url, status: status);

      if (mounted) {
        setState(() {
          // 触发UI更新
        });
      }
    };
    NativeVideoCacheManager.addStatusListener(_statusListener!);

    _errorListener = (String url, String error) {
      debugPrint('缓存错误: $url -> $error');
      CacheStateManager.instance
          .updateState(url, status: CacheStatus.error, errorMessage: error);

      if (mounted) {
        setState(() {
          // 触发UI更新
        });
      }
    };
    NativeVideoCacheManager.addErrorListener(_errorListener!);
  }

  @override
  Widget build(BuildContext context) {
    if (_isSingleVideoMode) {
      return _buildVideoPlayerMode();
    } else {
      return _buildMultiVideoMode();
    }
  }

  /// 构建视频播放器模式（单视频播放）
  Widget _buildVideoPlayerMode() {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        title: Text(_currentVideoTitle),
        backgroundColor: Colors.black,
        foregroundColor: Colors.white,
      ),
      body: Column(
        children: [
          // 播放器容器
          AspectRatio(
            aspectRatio: 16 / 9,
            child: Container(
              color: Colors.black,
              child: _isInitialized
                  ? NativeAvPlayerWidget(
                      controller: _controller,
                      showDefaultControls: false,
                    )
                  : _buildLoadingOrErrorWidget(),
            ),
          ),

          // 播放器信息和控制面板
          Expanded(
            child: Container(
              padding: const EdgeInsets.all(16),
              color: Colors.grey[900],
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 视频信息
                    Text(
                      _currentVideoTitle,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      _currentVideoUrl,
                      style: const TextStyle(
                        color: Colors.white70,
                        fontSize: 12,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 16),

                    // 状态信息
                    _buildPlayerStatusCard(),

                    const SizedBox(height: 16),

                    // 控制按钮
                    if (_isInitialized) _buildPlayerControls(),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建多视频管理模式
  Widget _buildMultiVideoMode() {
    return Scaffold(
      appBar: AppBar(
        title: const Text('优化的缓存演示'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 状态卡片
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '系统状态',
                      style: Theme.of(context).textTheme.titleMedium,
                    ),
                    const SizedBox(height: 8),
                    Text(_status),
                    if (_isManagerInitialized) ...[
                      const SizedBox(height: 16),
                      _buildSystemStats(),
                    ],
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 操作按钮
            if (_isManagerInitialized) ...[
              Text(
                '缓存操作',
                style: Theme.of(context).textTheme.titleMedium,
              ),
              const SizedBox(height: 8),
              Wrap(
                spacing: 8,
                children: [
                  ElevatedButton(
                    onPressed: _startAllCache,
                    child: const Text('开始全部缓存'),
                  ),
                  ElevatedButton(
                    onPressed: _stopAllCache,
                    child: const Text('停止全部缓存'),
                  ),
                  ElevatedButton(
                    onPressed: _clearAllCache,
                    child: const Text('清理全部缓存'),
                  ),
                  ElevatedButton(
                    onPressed: _showPerformanceReport,
                    child: const Text('性能报告'),
                  ),
                ],
              ),

              const SizedBox(height: 16),

              // URL列表
              Text(
                '缓存项目',
                style: Theme.of(context).textTheme.titleMedium,
              ),
              const SizedBox(height: 8),
              Expanded(
                child: ListView.builder(
                  itemCount: _testUrls.length,
                  itemBuilder: (context, index) {
                    final url = _testUrls[index];
                    return _buildUrlCard(url, index);
                  },
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildSystemStats() {
    final stateStats = CacheStateManager.instance.getStatistics();
    final memoryStats = CacheMemoryManager.instance.getMemoryStats();
    final stabilityStats = CacheStabilityManager.instance.getStabilityStats();

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('状态统计: ${stateStats['totalUrls']} 个URL'),
        Text('成功率: ${(stateStats['successRate'] * 100).toStringAsFixed(1)}%'),
        Text('内存监听器: ${memoryStats['totalListeners']}'),
        Text('重试任务: ${stabilityStats['totalRetryContexts']}'),
      ],
    );
  }

  Widget _buildUrlCard(String url, int index) {
    final state = CacheStateManager.instance.getState(url);
    final fileName = 'Video ${index + 1}';

    return Card(
      child: ListTile(
        title: Text(fileName),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              url,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(fontSize: 12),
            ),
            if (state != null) ...[
              const SizedBox(height: 4),
              Row(
                children: [
                  _buildStatusChip(state.status),
                  const SizedBox(width: 8),
                  Text('${(state.progress * 100).toStringAsFixed(1)}%'),
                ],
              ),
              if (state.progress > 0 && state.progress < 1)
                LinearProgressIndicator(value: state.progress),
            ],
          ],
        ),
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            IconButton(
              icon: const Icon(Icons.play_arrow),
              onPressed: () => _startSingleCache(url),
            ),
            IconButton(
              icon: const Icon(Icons.stop),
              onPressed: () => _stopSingleCache(url),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatusChip(CacheStatus status) {
    Color color;
    String text;

    switch (status) {
      case CacheStatus.none:
        color = Colors.grey;
        text = '未缓存';
        break;
      case CacheStatus.caching:
        color = Colors.blue;
        text = '缓存中';
        break;
      case CacheStatus.cached:
        color = Colors.green;
        text = '已缓存';
        break;
      case CacheStatus.error:
        color = Colors.red;
        text = '错误';
        break;
    }

    return Chip(
      label: Text(text, style: const TextStyle(fontSize: 12)),
      backgroundColor: color.withOpacity(0.2),
      side: BorderSide(color: color),
    );
  }

  Future<void> _startAllCache() async {
    for (final url in _testUrls) {
      await _startSingleCache(url);
    }
  }

  Future<void> _stopAllCache() async {
    for (final url in _testUrls) {
      await _stopSingleCache(url);
    }
  }

  Future<void> _startSingleCache(String url) async {
    try {
      // 直接使用原生缓存管理器
      await NativeVideoCacheManager.startCache(url);

      // 更新状态
      CacheStateManager.instance.updateState(url, status: CacheStatus.caching);

      // 注册到生命周期管理器
      AppLifecycleManager.instance.registerActiveUrl(url);

      debugPrint('开始缓存: $url');
    } catch (e) {
      debugPrint('开始缓存失败: $url - $e');
      CacheStateManager.instance.updateState(
        url,
        status: CacheStatus.error,
        errorMessage: e.toString(),
      );
    }
  }

  Future<void> _stopSingleCache(String url) async {
    try {
      await NativeVideoCacheManager.stopCache(url);
      CacheStateManager.instance.updateState(url, status: CacheStatus.none);
      AppLifecycleManager.instance.unregisterActiveUrl(url);
    } catch (e) {
      debugPrint('停止缓存失败: $e');
    }
  }

  Future<void> _clearAllCache() async {
    try {
      await NativeVideoCacheManager.clearAllCache();
      CacheStateManager.instance.clearAllStates();
      setState(() {
        _status = '所有缓存已清理';
      });
    } catch (e) {
      setState(() {
        _status = '清理缓存失败: $e';
      });
    }
  }

  void _showPerformanceReport() {
    final report = CachePerformanceMonitor.instance.getPerformanceReport();
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('性能报告'),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text('总URL数: ${report['totalUrls']}'),
              Text(
                  '成功率: ${(report['overallSuccessRate'] * 100).toStringAsFixed(1)}%'),
              Text(
                  '平均耗时: ${report['averageDuration']?.toStringAsFixed(1) ?? 'N/A'}秒'),
              Text('总错误数: ${report['totalErrors']}'),
              Text('最近事件数: ${report['recentEventCount']}'),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  /// 构建加载或错误显示Widget
  Widget _buildLoadingOrErrorWidget() {
    // 如果有详细的错误信息，显示友好的错误界面
    if (_currentErrorInfo != null) {
      final errorInfo = _currentErrorInfo!;

      return Container(
        color: Colors.black,
        padding: const EdgeInsets.all(20),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 错误图标
              Text(
                errorInfo.icon,
                style: const TextStyle(fontSize: 48),
              ),
              const SizedBox(height: 16),

              // 错误标题
              Text(
                errorInfo.title,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 8),

              // 错误描述
              Text(
                errorInfo.message,
                style: const TextStyle(
                  color: Colors.white70,
                  fontSize: 14,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 16),

              // 解决建议
              if (errorInfo.suggestions.isNotEmpty) ...[
                const Text(
                  '解决建议:',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 8),
                ...errorInfo.suggestions.take(3).map(
                      (suggestion) => Padding(
                        padding: const EdgeInsets.symmetric(vertical: 2),
                        child: Row(
                          children: [
                            const Text(
                              '• ',
                              style: TextStyle(color: Colors.white70),
                            ),
                            Expanded(
                              child: Text(
                                suggestion,
                                style: const TextStyle(
                                  color: Colors.white70,
                                  fontSize: 12,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                const SizedBox(height: 16),
              ],

              // 重试按钮
              if (errorInfo.canRetry)
                ElevatedButton.icon(
                  onPressed: () {
                    // 重新初始化播放器
                    _initializePlayer();
                  },
                  icon: const Icon(Icons.refresh),
                  label: const Text('重试'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blue,
                    foregroundColor: Colors.white,
                  ),
                ),
            ],
          ),
        ),
      );
    }

    // 默认的加载界面
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
          ),
          const SizedBox(height: 16),
          Text(
            _status,
            style: const TextStyle(color: Colors.white),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  /// 构建播放器状态卡片
  Widget _buildPlayerStatusCard() {
    return Card(
      color: Colors.grey[800],
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '播放器状态',
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 8),
            if (_isInitialized) ...[
              _buildStatusRow('状态', _status),
              _buildStatusRow('是否播放', _controller.isPlaying ? '是' : '否'),
              _buildStatusRow('是否缓冲', _controller.isBuffering ? '是' : '否'),
              _buildStatusRow('当前位置', _formatDuration(_controller.position)),
              _buildStatusRow('总时长', _formatDuration(_controller.duration)),
              _buildStatusRow(
                  '宽高比', _controller.aspectRatio.toStringAsFixed(2)),
              _buildStatusRow('代理URL', _controller.proxyUrl ?? '无'),
              const Divider(color: Colors.white54),
              _buildStatusRow('缓存状态', _getCacheStatusText(_cacheStatus)),
              _buildStatusRow(
                  '缓存进度', '${(_cacheProgress * 100).toStringAsFixed(1)}%'),
              if (_cacheProgress > 0)
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 4),
                  child: LinearProgressIndicator(
                    value: _cacheProgress,
                    backgroundColor: Colors.white24,
                    valueColor: AlwaysStoppedAnimation<Color>(
                      _cacheStatus == CacheStatus.cached
                          ? Colors.green
                          : Colors.blue,
                    ),
                  ),
                ),
            ] else
              Text(
                _status,
                style: const TextStyle(color: Colors.white70),
              ),
          ],
        ),
      ),
    );
  }

  /// 构建播放器控制按钮
  Widget _buildPlayerControls() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '快捷控制',
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 8),
        Wrap(
          spacing: 8,
          children: [
            ElevatedButton(
              onPressed: _controller.play,
              child: const Text('播放'),
            ),
            ElevatedButton(
              onPressed: _controller.pause,
              child: const Text('暂停'),
            ),
            ElevatedButton(
              onPressed: _controller.stop,
              child: const Text('停止'),
            ),
            ElevatedButton(
              onPressed: () => _controller.setPlaybackSpeed(0.5),
              child: const Text('0.5x'),
            ),
            ElevatedButton(
              onPressed: () => _controller.setPlaybackSpeed(1.0),
              child: const Text('1.0x'),
            ),
            ElevatedButton(
              onPressed: () => _controller.setPlaybackSpeed(2.0),
              child: const Text('2.0x'),
            ),
            ElevatedButton(
              onPressed: _controller.toggleFullScreen,
              child: const Text('全屏'),
            ),
            ElevatedButton(
              onPressed: _testCache,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
              ),
              child: const Text('测试缓存'),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildStatusRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              '$label:',
              style: const TextStyle(color: Colors.white70, fontSize: 12),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(color: Colors.white, fontSize: 12),
            ),
          ),
        ],
      ),
    );
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final hours = duration.inHours;
    final minutes = duration.inMinutes.remainder(60);
    final seconds = duration.inSeconds.remainder(60);

    if (hours > 0) {
      return '$hours:${twoDigits(minutes)}:${twoDigits(seconds)}';
    } else {
      return '$minutes:${twoDigits(seconds)}';
    }
  }

  String _getCacheStatusText(CacheStatus status) {
    switch (status) {
      case CacheStatus.none:
        return '未缓存';
      case CacheStatus.caching:
        return '缓存中';
      case CacheStatus.cached:
        return '已缓存';
      case CacheStatus.error:
        return '缓存错误';
    }
  }

  Future<void> _testCache() async {
    try {
      // 强制开始缓存当前视频
      await NativeVideoCacheManager.startCache(_currentVideoUrl);

      // 显示测试结果
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('缓存测试已启动，请观察缓存状态和进度变化'),
            backgroundColor: Colors.green,
            duration: Duration(seconds: 3),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('缓存测试失败: $e'),
            backgroundColor: Colors.red,
            duration: const Duration(seconds: 3),
          ),
        );
      }
    }
  }
}
